package ru.overtake;

/**
 * VKAPI class for vkontakte.ru social network
 *
 * @package server API methods
 * @link http://vk.com/developers.php
 * @autor Mihail Filimonov
 * @email overtakeful@gmail.com
 * @version 1.0
 */

import java.util.*;
import java.net.*;
import java.io.*;
import java.security.MessageDigest;

class MD5 {
	private String md5;

	public String getHash(String input) {
		try {
			StringBuilder code = new StringBuilder();
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			byte bytes[] = input.getBytes();
			byte digest[] = messageDigest.digest(bytes);

			for (int i = 0; i < digest.length; ++i)
				code.append(Integer.toHexString(0x0100 + (digest[i] & 0x00FF))
						.substring(1));

			md5 = code.toString();

		} catch (Exception e) {
		}

		return md5;
	}

}

class VKApi extends MD5 {
	private String api_secret;
	private int api_id;
	private TreeMap param = new TreeMap();

	public VKApi(String api_secret, int api_id) {
		this.api_secret = api_secret;
		this.api_id = api_id;
	}

	public String api(String Method) {
		return buildMethod(Method);
	}

	public Object api(String Method, TreeMap params) {

		Object[] keys = params.keySet().toArray();
		for (int i = 0; i < params.size(); i++)
			param.put(keys[i], params.get(keys[i]));

		return buildMethod(Method);

	}

	private String buildURL(TreeMap param) {

		String api_url = "http://api.vkontakte.ru/api.php?";
		StringBuilder sig = new StringBuilder();
		Object[] keys = param.keySet().toArray();

		for (int i = 0; i < param.size(); i++)
			sig.append(keys[i] + "=" + param.get(keys[i]));

		sig.append(this.api_secret);
		sig = new StringBuilder(getHash(sig.toString()));
		param.put("sig", sig);
		try {

			keys = param.keySet().toArray();
			for (int i = 0; i < param.size(); i++)
				api_url += keys[i]
						+ "="
						+ URLEncoder.encode((param.get(keys[i])).toString(),
								"UTF-8") + "&";

		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}

		return query(api_url);
	}

	private String query(String url) {
		URLConnection query;
		InputStream result;
		String data;
		byte buf[] = new byte[1024 * 48];
		try {
			query = new URL(url).openConnection();
			result = query.getInputStream();
			int r = result.read(buf);
			data = new String(buf, 0, r);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		param.clear();
		return data;
	}

	private String buildMethod(String Method) {
		Date date = new Date();
		long now = date.getTime() / 1000;

		param.put("api_id", this.api_id);
		param.put("v", "3.0");
		param.put("method", Method);
		param.put("timestamp", now);
		param.put("format", "json");
		param.put("random", Math.round(Math.random() * 1000));
		return buildURL(param);
	}
}